package com.gopay.webtest.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.webtest.controller.base.BaseController;
import com.gopay.webtest.util.BaseSign;
import com.gopay.webtest.util.ReflectUtil;
import com.gopay.webtest.vo.PayInfo;
import com.gopay.webtest.xml.XmlDao;

/**
 * wap支付
 * 
 * @author wangxintao
 */
@SuppressWarnings("all")
@Controller
public class WapPayController extends BaseController {
    
    private static final String CHARSET_GBK = "1";
    
    @Resource(name = "paySignHandler")
    private BaseSign paySignHandler;
    
    private static Map<String, String> map = null;
    
    @Autowired
    public WapPayController(@Qualifier(value = "xmlDao") XmlDao xmlDao) {
        try {
            map = xmlDao.readData4Map("pay", "payapply");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * pay url mapping view controller
     * 
     * @return
     */
    @RequestMapping("/wap_pay")
    public ModelAndView pay() {
//        StopWatch sw  = new StopWatch();
//        sw.start();
        ModelAndView mav = new ModelAndView();
        PayInfo payinfo = getDefaultInfoFromXML();
        mav.setViewName("gopay.webtest.wap_pay");
        mav.addObject("payInfo", payinfo);
//        sw.stop();
//        log.info("打开网关支付默认页面，耗时:"+sw.getTime());
        return mav;
    } 
 
    private PayInfo getDefaultInfoFromXML() {
        PayInfo payInfo = new PayInfo();

        payInfo.setMerchantID((String) map.get("merchantID"));
        payInfo.setBackgroundMerUrl((String) map.get("backgroundMerURL"));
        payInfo.setCurrencyType((String) map.get("currType"));
        payInfo.setMerURL((String) map.get("merURL"));
        payInfo.setTranDateTime(com.gopay.webtest.util.DateUtils.date2string(new Date(), com.gopay.webtest.util.DateUtils.DEFAULT_PATTERN));
        payInfo.setTranIP((String) map.get("tranIP"));
        payInfo.setVirCardNoIn((String) map.get("virCardNoIn"));

        return payInfo;
    } 

    /**
     * 提交订单到支付宝
     * 
     * @param payInfo
     * @return
     */
    @RequestMapping("/wap_paySubmit")
    public ModelAndView paySubmit(PayInfo payInfo) {
    	//{sign=/Trans/BlockTrade.do, tradeQuery=/Trans/WebClientAction.do, apply=/Trans/WebClientAction.do, tradeQuery4027=/Trans/WebClientAction.do, bankres=/Trans/TestBankPayRes.do, dom=http://localhost:8080/gateway, tradeQuery4028=/Trans/WebClientAction.do, blocktrade=/Trans/BlockTrade.do, pay=/Trans/WebClientAction.do, auth=/Trans/WebClientAction.do, p2p=/Trans/P2P.do, goodsreturn=/Trans/WebClientAction.do}
        ModelAndView mav = new ModelAndView();
        String backgroundMerUrl = payInfo.getBackgroundMerUrl();
        if (backgroundMerUrl != null && !backgroundMerUrl.equals("")) {
            backgroundMerUrl = backgroundMerUrl + "?id=" + payInfo.getVerficationCode();
        }

        String frontMerUrl = payInfo.getFrontMerUrl();
        if (frontMerUrl != null && !frontMerUrl.equals("")) {
            frontMerUrl = frontMerUrl + "?id=" + payInfo.getVerficationCode();
        }
        payInfo.setBackgroundMerUrl(backgroundMerUrl);
        payInfo.setFrontMerUrl(frontMerUrl);
        
        StopWatch sw  = new StopWatch();
        
        // 设置MD5加密字段
        try {
            sw.start();
            paySignHandler.sign(payInfo.getTranCode() + "_" + payInfo.getVersion(), "signType", "signValue", payInfo, getRequest());
            sw.stop();
            logger.info("step1 time:"+sw.getTime());
            logger.info("后台notify密文值:" + payInfo.getSignValue());
            
            String buyerName = payInfo.getBuyerName();
            if (StringUtils.equals(buyerName, "MWAP")) {
            	//如果是mwap 则跳到 mp项目  需要对 merReark2 进行 签名处理
            	//"version=["+version+"]tranCode=["+tranCode+"]merchantID=["+merchantID+"]merOrderNum=["+merOrderNum+"]buyerContact=["
				//+buyerContact+"]VerficationCode=["+verify_code+"]"
            	StringBuffer sb = new StringBuffer();
            	sb.append(getSignStr("version", payInfo));
            	sb.append(getSignStr("tranCode", payInfo));
            	sb.append(getSignStr("merchantID", payInfo));
            	sb.append(getSignStr("merOrderNum", payInfo));
            	sb.append(getSignStr("buyerContact", payInfo));
            	sb.append("VerficationCode=[" + payInfo.getVerficationCode() + "]");
            	System.out.println("mwap 参数merRemark2 签名原串=" + sb.toString());
            	String sign = DigestUtils.md5Hex(sb.toString().getBytes("UTF-8"));
            	System.out.println("mwap 参数merRemark2 签名后=" + sign);
            	
            	payInfo.setMerRemark2(sign);
            }
            
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        String signedValue = payInfo.getSignValue();
        /* 是否是wap支付标志位 */
        String isWapPay = payInfo.getIsWapPay();
        if (null == signedValue) {
            // 加密操作失败,置返回码为身份认证md5加密失败
            payInfo.setRespCode("MR08");
            mav.setViewName("gopay.webtest.wap_pay");
        } else if (StringUtils.isNotEmpty(isWapPay) && "1".equals(isWapPay)) {
            mav.setViewName("gopay.webtest.wap_pay");
        } else {
            mav.setViewName("gopay.webtest.wap_payFormSubmitFormSubmit");
        }
        if (!payInfo.getCharset().equals("2")) {
            mav.setViewName("gopay.webtest.wap_payFormSubmit_gbk");
        } else {
            mav.setViewName("gopay.webtest.wap_payFormSubmit");
        }
        mav.addObject("payInfo", payInfo);
        return mav;
    }

    
    private String getSignStr(String fieldName, Object obj) throws Exception  {
    	StringBuffer sb = new StringBuffer(fieldName + "=[");
    	String str =  ReflectUtil.getFieldValue(obj, fieldName);
    	sb.append(str);
    	sb.append("]");
    	
    	return sb.toString();
    }
    
    public ModelAndView payRe(PayInfo payInfo) {
        logger.info(payInfo.getRespCode());
        String ss = payInfo.getSignValue();
        
        payInfo.setVerficationCode((String) map.get("verficationCode"));
        ModelAndView mav = new ModelAndView();

        // 设置MD5加密字段
        try {
            paySignHandler.sign(payInfo.getTranCode(), payInfo.getSignType(), "signValue", payInfo, getRequest());
            logger.info("后台notify密文值:" + payInfo.getSignValue());
            logger.info("后台通知webtest校验密文值:" + ss);
            logger.info("---------------校验结果：" + payInfo.getSignValue().equals(ss));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!CHARSET_GBK.equalsIgnoreCase(payInfo.getCharset())) {
            mav.setViewName("gopay.webtest.wap_payFormSubmit");
        } else {
            mav.setViewName("gopay.webtest.wap_payFormSubmit_gbk");
        }

        mav.addObject("payInfo", payInfo);
        return mav;
    }
}
